﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Net;
using System.Text;
using System.Windows.Forms;

namespace Serviio.WHS2011
{
    public partial class ServiioDownloadForm : Form
    {
        private static readonly LogFacade log = LogFacade.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public ServiioDownloadForm()
        {
            InitializeComponent();
        }

        private string localFileName = null;
        private WebClient wc = new WebClient();

        public string Download()
        {
            try
            {
                string fileName = Properties.Settings.Default.ServiioDownloadFile;
                string url = Properties.Settings.Default.ServiioDownloadHost + fileName;
                string tempDir = System.Environment.GetEnvironmentVariable("TEMP") ?? "c:";
                localFileName = tempDir + "\\" + fileName;

                if (!System.IO.File.Exists(localFileName))
                {
                    wc.DownloadFileCompleted += DownloadFileCompleted;
                    wc.DownloadProgressChanged += DownloadProgressChanged;
                    wc.DownloadFileAsync(new Uri(url), localFileName);

                    this.ShowDialog();
                }
                if (System.IO.File.Exists(localFileName))
                    return localFileName;
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
            return null;
        }

        private void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            try
            {
                progressBarDownload.Value = e.ProgressPercentage;
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled && System.IO.File.Exists(localFileName))
                    System.IO.File.Delete(localFileName);
                this.DialogResult = e.Cancelled ? DialogResult.Cancel : DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        private void ServiioDownloadForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (wc.IsBusy)
                {
                    wc.CancelAsync();
                    e.Cancel = true;
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }
    }
}
